package ncc.bs.Plugins;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.itf.pub.dbservice.IDBService;
import nc.jdbc.framework.generator.IdGenerator;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.vo.pub.BusinessException;
import ncc.bs.Plugins.cz.CZBusinessSQL;
import nccloud.bs.log.LogVO;
import nccloud.tool.copro.report.StringUtils;
import nccloud.utils.baseapp.HttpReqUtils;
import nccloud.utils.baseapp.InitParamUtils;
import nccloud.utils.baseapp.ToolUtils;

/** 
 * <p>同步财政系统</p>
 * 单位会计凭证分录表--凭证明细表
 * @author Administrator
 * @date 2024年2月27日
 */
public class VoucherDetailBackGroundWorkPlugin extends AbstractBackgroundWorkPlugin{
	private BaseDAO dao;
	private final SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
	private final SimpleDateFormat ymdsfm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private IDBService dbService;

	@SuppressWarnings({ "rawtypes", "unused" })
	@Override
	public void doBusiness(Map keyMap) throws BusinessException {
		String sql = CZBusinessSQL.builderCZ_GLA_VOU_DETAIL(keyMap);
		List<Map<String, Object>> lists = queryData(sql);
		try {
			List<List<Map<String,Object>>> listparams = super.getGroupAfterData(lists);
			if(listparams == null ) return;
			// 对分组的数据进行推送
			for(List<Map<String, Object>> params : listparams) {
				List<LogVO> listVOs = new ArrayList<>();
				String message = null;
				String issuccess = "Y";
				String result = null;
				try {
					String param = super.getParam(buildParam(params,listVOs),"DWKJHS06", super.getAppid()); // 每十行数据合并在一起推送
					if(param == null || "".equals(param)) return;
					result = HttpReqUtils.sendPost(getURL("DEF001"), param);
					getLog().info("----第四步接口响应结果::" + result);
					JSONObject jsonres = JSONObject.parseObject(result);
					Object code = jsonres.get("code");
					if("200".equals(code)) {
						message = "同步成功";
					}else {
						issuccess = "N";
						message = jsonres.getString("msg"); 
						result = jsonres.toString();
					}
					
				}catch(Exception e) {
					message = e.getMessage();
					issuccess = "N";
					getLog().error("凭证主表同步异常:【"+message+"】");
				}finally {
					for(LogVO vo : listVOs) {
						vo.setIssuccess(issuccess);
						vo.setError(message);
						vo.setVdef2(result);
						
					}
					getDbService().insertVOList(listVOs);
				}
			}
		}catch(Exception e) {
			LogVO vo = new LogVO();
			vo.setPk_id(NCLocator.getInstance().lookup(IdGenerator.class).generate());
			vo.setIssuccess("N");
			vo.setPk_group("0001A210000000000JB9");
			vo.setPk_billtypeid("voucherDetail");
			vo.setSystem_flag("financial");
			vo.setVdef1("拉取参数、类型:"+ keyMap.get("type")+",开始日期:"+keyMap.get("begindate")+"结束日期:"+keyMap.get("enddate")+",同步频率:"+keyMap.get("synctime"));
			vo.setError("会计科目同步:"+e.getMessage());
			getDbService().insertVO(vo);
		}
	}

	/**
	 *
	 * 查询需要同步的数据
	 * @param sql
	 * @return
	 * @throws BusinessException
	 */
	@SuppressWarnings("unchecked")
	public List<Map<String, Object>>  queryData(String sql)  throws BusinessException{
		if(sql == null) return null;
		List<Map<String, Object>> lists = (List<Map<String, Object>>)getDao().executeQuery(sql, new MapListProcessor());
		return lists == null ||  lists.isEmpty() ? null : lists;
	}
	
	/**
	 * 构建请求参数
	 * @return
	 * @throws Exception 
	 */
	public JSONArray buildParam(List<Map<String, Object>> data,List<LogVO> listVOs) throws Exception{
		if(data == null) return null;
		JSONArray jsonArray = new JSONArray();
		for(Map<String, Object> map : data) {
			JSONObject json = new JSONObject();
			json.put("VOU_DET_ID", ToolUtils.getJudgeAttribute(map.get("vou_det_id"))); // 凭证分录唯一标识
			json.put("VOU_ID", ToolUtils.getJudgeAttribute(map.get("vou_id")));  // 凭证主表唯一标识
			json.put("MOF_DIV_CODE", super.getMOF_DIV_CODE()); // 财政区划代码
			json.put("SET_YEAR", ToolUtils.getJudgeAttribute(map.get("set_year"))); // // 会计年度
			json.put("ACCT_SET_CODE", super.getAccount());  // 账套编号
			json.put("ACCT_PERIOD", ToolUtils.getJudgeAttribute(map.get("acct_period"))); //会计期间
			json.put("AGENCY_CODE", super.getUnit()); // 单位代码
			json.put("ACCT_SET_NAME", super.getACCT_SET_NAME());  // 账套名称
			json.put("AGENCY_NAME", super.getAGENCY_NAME()); // 单位名称
			json.put("VOUCHER_NO", ToolUtils.getJudgeAttribute(map.get("voucher_no"))); // 凭证号
			json.put("VOU_SEQ", ToolUtils.getJudgeAttribute(map.get("vou_seq"))); // 记账凭证分录序号
			json.put("GOV_ACCT_CLS_CODE", ToolUtils.getJudgeAttribute(map.get("gov_acct_cls_code"))); // 单位会计科目代码
			json.put("GOV_ACCT_CLS_NAME", ToolUtils.getJudgeAttribute(map.get("gov_acct_cls_name"))); // 单位会计科目名称
			json.put("DR_CR", map.get("dr_cr") == null ? 0 : map.get("dr_cr"));
			json.put("AMT", map.get("amt") == null ? 0 : map.get("amt"));
			json.put("FOREIGN_AMT", map.get("foreign_amt") == null ?0 : map.get("foreign_amt"));
			json.put("EXT_RAT", ToolUtils.getJudgeAttribute(map.get("ext_rat")));
			json.put("CURRENCY_CODE", ToolUtils.getJudgeAttribute(map.get("currency_code"))); // 币种代码
			json.put("QTY", map.get("qty") == null ? 0 : map.get("qty"));
			json.put("PRO_CODE", ToolUtils.getJudgeAttribute(map.get("pro_code")));
			json.put("GOV_BGT_ECO_CODE", ToolUtils.getJudgeAttribute(map.get("gov_bgt_eco_code")));
			json.put("DEPARTMENT_CODE", ToolUtils.getJudgeAttribute(map.get("department_code")));
			json.put("EMPLOYEE_CODE", ToolUtils.getJudgeAttribute(map.get("employee_code")));
			json.put("FUND_TRA_OBJ_NO", ToolUtils.getJudgeAttribute(map.get("fund_tra_obj_no")));
			json.put("FUND_TRA_OBJ_NAME", ToolUtils.getJudgeAttribute(map.get("fund_tra_obj_name")));
			json.put("DUE_DATE", ToolUtils.getJudgeAttribute(map.get("due_date")));
			json.put("EXP_FUNC_CODE", ToolUtils.getJudgeAttribute(map.get("exp_func_code")));
			json.put("FUND_TYPE_CODE", ToolUtils.getJudgeAttribute(map.get("fund_type_code")));
			json.put("FOUND_TYPE_CODE", ToolUtils.getJudgeAttribute(map.get("found_type_code")));
			json.put("PAY_BUS_TYPE_CODE", ToolUtils.getJudgeAttribute(map.get("pay_bus_type_code")));
			json.put("PAY_TYPE_CODE", ToolUtils.getJudgeAttribute(map.get("pay_type_code")));
			json.put("SET_MODE_CODE", ToolUtils.getJudgeAttribute(map.get("set_mode_code")));
			json.put("PUR_MET_CODE", ToolUtils.getJudgeAttribute(map.get("pur_met_code")));
			json.put("FATYPE_CODE", ToolUtils.getJudgeAttribute(map.get("fatype_code")));
			json.put("COST_TYPE_CODE", ToolUtils.getJudgeAttribute(map.get("cost_type_code")));
			json.put("BILL_DATE", ToolUtils.getJudgeAttribute(map.get("bill_date")));
			json.put("COR_BGT_DOC_NO", ToolUtils.getJudgeAttribute(map.get("cor_bgt_doc_no")));
			json.put("BUDGET_LEVEL_CODE", ToolUtils.getJudgeAttribute(map.get("budget_level_code")));
			json.put("SUP_BGT_DOC_NO", ToolUtils.getJudgeAttribute(map.get("sup_bgt_doc_no")));
			json.put("ORI_PRO_CODE", ToolUtils.getJudgeAttribute(map.get("ori_pro_code")));
			json.put("BGT_TYPE_CODE", ToolUtils.getJudgeAttribute(map.get("bgt_type_code")));
			json.put("MOF_DEP_CODE", ToolUtils.getJudgeAttribute(map.get("mof_dep_code")));
			json.put("DEP_BGT_ECO_CODE", ToolUtils.getJudgeAttribute(map.get("dep_bgt_eco_code")));
			json.put("AUX01", ToolUtils.getJudgeAttribute(map.get("aux01"))); // 现金流量项目
			json.put("AUX02", ToolUtils.getJudgeAttribute(map.get("aux02"))); // 客户
			json.put("AUX03", ToolUtils.getJudgeAttribute(map.get("aux03"))); // 供应商
			json.put("AUX04", ToolUtils.getJudgeAttribute(map.get("aux04"))); // 经费类型
			json.put("AUX05", ToolUtils.getJudgeAttribute(map.get("aux05"))); // 支付对象
			json.put("AUX06", ToolUtils.getJudgeAttribute(map.get("aux06"))); // 指令性任务
			json.put("AUX07", ToolUtils.getJudgeAttribute(map.get("aux07"))); // 收入来源
			json.put("AUX08", ToolUtils.getJudgeAttribute(map.get("aux08"))); // 拨款种类
			json.put("AUX09", ToolUtils.getJudgeAttribute(map.get("aux09"))); // 项目类型

			String VOU_DET_DESC = "";
			if (null != map.get("vou_det_desc") || !"".equals(map.get("vou_det_desc").toString())){
				if(map.get("vou_det_desc").toString().length() > 400){
					VOU_DET_DESC = map.get("vou_det_desc").toString().substring(0,150);
				}else{
					VOU_DET_DESC = map.get("vou_det_desc").toString();
				}
			}
			json.put("VOU_DET_DESC", VOU_DET_DESC);
			json.put("AGENCY_ACCT_VOUCHER_TYPE", "JZ");
			json.put("AGENCY_ACCT_VOUCHER_NAME", "记账"); // 单位会计记账凭证类型
			json.put("UPDATE_TIME", super.getYMDHMS(map.get("update_time"))); // 更新时间
			json.put("CREATE_TIME", super.getYMDHMS(map.get("create_time")));
			json.put("IS_DELETED", map.get("is_deleted")); // 1已删除 2 未删除
			LogVO logVO = getDbService().buildLogVO(map, json, "financial", "voucherDetail");
			listVOs.add(logVO);
			jsonArray.add(json);
		}
		return jsonArray;
	}
	
	/**
	 * 获取第三方同步地址
	 * @param initCode
	 * @return
	 * @throws Exception
	 */
	public String getURL(String initCode) throws Exception{
		String url = InitParamUtils.getOrgParam("GLOBLE00000000000000",initCode)+"/pty/gla-dec/v1/voucher/details";
		getLog().info("----第三步接口请求地址:" + url);
		return url;
	}

	/**
	 * 数据库操作服务
	 * @return
	 */
	public IDBService getDbService() {
		if(dbService == null) {
			dbService = NCLocator.getInstance().lookup(IDBService.class);
		}
		return dbService;
	}

	public BaseDAO getDao() {
		return dao == null ? new BaseDAO() : dao ;
	}
}
